<template>
  <div id="total">
    <!-- 顶部接诊以及按钮 -->
    <div id="top">
      <!-- 左边接诊 -->
      <div id="left">
        <span>接诊</span>
      </div>
      <!-- 右边按钮 -->
      <div id="right">
        <!-- 历史按钮 -->
        <el-button id="btn-r" type="primary" @click="searchHistory">历史</el-button>
        <!-- 历史弹窗 -->
        <el-drawer v-model="table" title="历史" direction="rtl" size="40%">
          <div class="mt-4">
            <el-input v-model="input4" placeholder="姓名或手机号" class="input-with-select1">
              <template #append>
                <el-button :icon="Search" />
              </template>
            </el-input>
            <el-form-item label="缴费状态">
              <el-select v-model="form1.region" placeholder="全部">
                <el-option label="未支付" value="0" />
                <el-option label="已支付" value="1" />
                <el-option label="确认收款" value="2" />
                <el-option label="已退款" value="3" />
                <el-option label="部分退款" value="4" />
                <el-option label="全部" value="5" />
              </el-select>
            </el-form-item>
          </div>

          <el-table :data="historyData" @row-click="setInfo">
            <el-table-column property="patientBankRef.bankName" label="姓名" width="150" />
            <el-table-column property="patientBankRef.phone" label="手机号" width="200" />
            <el-table-column property="seeDoctorTime" label="时间" />
            <el-table-column label="状态">
              <template #default="scope">
                <span v-if="scope.row.status == 0">未支付</span>
                <span v-if="scope.row.status == 1">已支付</span>
                <span v-if="scope.row.status == 2">确认收款</span>
                <span v-if="scope.row.status == 3">已退款</span>
                <span v-if="scope.row.status == 4">部分退款</span>
                <span v-if="scope.row.status == 5">全部</span>
              </template>
            </el-table-column>
          </el-table>
        </el-drawer>
        <!-- 保存按钮 -->
        <el-button type="success" @click="saveData">保存</el-button>
      </div>
    </div>
    <!-- 内容部分 -->
    <div id="content">
      <!-- 左边患者信息部分 -->
      <div id="content_left">
        <!-- 患者信息标题 -->
        <div id="title">
          <span id="blue">患者信息</span>
        </div>
        <!-- 患者信息表格 -->
        <div id="p_form">
          <el-form :model="patientInfo" label-width="100px">
            <el-form-item label="姓名:">
              <div id="inputk">
                <el-input id="inputk" placeholder="请输入姓名" v-model="patientInfo.bankName" @blur="test" />
              </div>
              <el-button id="name" @click="dialogTableVisible = true" :icon="Search" circle />
              <!-- 弹出框 -->
              <el-dialog v-model="dialogTableVisible" title="选择患者">
                <!-- 选择按钮 -->
                <nav>
                  <ul>
                    <li id="gua" :class="btn5" @click="Registration()">
                      挂号列表
                    </li>
                    <li id="huan" :class="btn6" @click="Patient()">患者库</li>
                  </ul>
                </nav>

                <!-- 下面是否显示 -->
                <vue5 v-if="flagTwo" />
                <vue6 v-if="!flagTwo" />
              </el-dialog>
            </el-form-item>
            <div id="sex">
              <span id="word">性别:&nbsp;&nbsp;&nbsp;</span>
              <el-select v-model="patientInfo.sex" class="m-2" placeholder="男">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <div id="f">
              <div id="f_left">
                <el-form-item label="生日:">
                  <el-col :span="18.2">
                    <el-date-picker v-model="patientInfo.birthday" type="date" placeholder="您的生日日期" style="width: 100%"
                      @input="computedAgeFunc" />
                  </el-col>
                </el-form-item>
              </div>
              <div id="f_right">
                <span>年龄:&nbsp;{{ computedAge }}</span>
              </div>
            </div>

            <el-form-item label="手机号码:">
              <el-input placeholder="请输入手机号码" v-model="patientInfo.phone" 
                @input="searchTel"
              />
            </el-form-item>
            <!-- 住址 -->
            <el-form-item label="住址:">
              <el-input placeholder="填写当前住址(限100字)" v-model="patientInfo.address" type="textarea" />
            </el-form-item>
            <!-- 过敏史 -->
            <el-form-item label="过敏史:">
              <el-input placeholder="填写本次诊断详情(限500字)" v-model="patientInfo.allergicHistory" type="textarea" />
            </el-form-item>
          </el-form>
        </div>
        <!-- 两个切换按钮 -->
        <nav>
          <ul>
            <li :class="btn1" @click="patientFile()">患者档案</li>
            <li :class="btn2" @click="historicalCase()">历史病例</li>
          </ul>
        </nav>
        <!-- 下面是否显示 -->
        <vue1 v-if="flag" />
        <vue2 v-if="!flag" />
      </div>
      <!-- 右边病例or处方部分 -->
      <div id="content_right">
        <div id="r_inner">
          <!-- 顶部切换按钮 -->
          <div id="toggleButton">
            <!-- 两个切换按钮 -->
            <nav id="nav">
              <ul>
                <li id="li" :class="btn3" @click="caseOne()">病例</li>
                <li id="li" :class="btn4" @click="prescription()">处方</li>
              </ul>
            </nav>
            <!-- 下面是否显示 -->
            <vue3 v-if="flagOne" @submitData="submitRefData" />
            <vue4 v-if="!flagOne" @submitData="submitRxsData" :isAdd="true" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUpdated, onBeforeUpdate } from "vue";
import vue1 from "@/components/newly/a.vue";
import vue2 from "@/components/newly/b.vue";
import vue3 from "@/components/newly/d.vue";
import vue4 from "@/components/newly/c.vue";
import vue5 from "@/components/newly/registration.vue";
import vue6 from "@/components/newly/patient.vue";
import { Search } from "@element-plus/icons-vue";
import { useStore, mapGetters, mapMutations } from "vuex";
import router from "@/router";
import { ElMessage } from "element-plus";
import axios from "@/utils/http";
const store = useStore();
const patientInfoNet = computed(mapGetters(["getPatientInfo"]).getPatientInfo.bind({ $store: store, }))
const historyData = computed(mapGetters(["getHistoryData"]).getHistoryData.bind({ $store: store, }))
const createTreat = mapMutations(["createTreat"]).createTreat.bind({ $store: store, })
const searchHis = mapMutations(["searchHis"]).searchHis.bind({ $store: store, })
const setInfoById = mapMutations(["setInfoById"]).setInfoById.bind({ $store: store, })

const patientInfo = ref(patientInfoNet.value) 
const searchHistory = () => {
  table.value = true;
}
const setInfo = async (row: any) => {
  table.value = false;
  await axios({
      url:"/diagnose/queryScriptBydiaId",
      method:"get",
      params:{
        diagnoseId:row.id
      }
      }).then((res:any)=>{
        store.state.createTreat.patientInfo=res.data.data
      }).catch(err=>{
        console.log(err);
      })
  patientInfo.value = patientInfoNet.value //----------------测试线上数据覆盖更新--------
}
const test = () => {
  console.log("blurtest", patientInfo.value);
}
onMounted(() => {
  searchHis()
})
const computedAge = ref("")
const computedAgeFunc = () => {
  let date = new Date(patientInfo.value.birthday)
  let date2 = new Date()
  let haomiao = date2.getTime() - date.getTime()
  haomiao = Math.ceil(haomiao / (1000 * 60 * 60 * 24))
  console.log(haomiao);
  if (haomiao < 30) {
    computedAge.value = haomiao + "天"
    patientInfo.value.age = 0
  } else if (haomiao < 365) {
    computedAge.value = Math.floor(haomiao / 30) + "个月"
    patientInfo.value.age = 0
  } else {
    computedAge.value = Math.floor(haomiao / 365) + "岁"
    patientInfo.value.age = Math.floor(haomiao / 365);
  }
}
let submitRef: any = null;
const submitRefData = (ref: any) => {
  submitRef = JSON.parse(JSON.stringify(ref.value))
  console.log("father1Ref", submitRef);
}
let submitRxs: any = null;
const submitRxsData = (rxs: any) => {
  submitRxs = JSON.parse(JSON.stringify(rxs.value))
  console.log("father2Rxs", submitRxs);
}
const saveData = async () => {
  if (!store.state.router.userData.userInfo.empUserName) {
    ElMessage({
      message: "请先登录！"
    });
    router.push({ path: "/login" })
    return;
  }
  if (!submitRxs || !submitRxs.length) {
    ElMessage({
      message: "请先添加处方"
    });
    return;
  }
  if (!submitRef) {
    ElMessage({
      message: "请填写就诊信息"
    });
    return;
  }
  
  let dateP = new Date().getTime();
  let recordsId = Number(getRandomStr(8))
  let seeDoctorId = Number(getRandomStr(8))
  //用户信息
  let patientBankVo = JSON.parse(JSON.stringify(patientInfo.value));
  console.log(patientBankVo);
  
  patientBankVo = {
    "address": patientBankVo.address,
    "age": patientBankVo.age,
    "allergicHistory": patientBankVo.allergicHistory,
    "bankId": patientBankVo.bankId,
    "bankName": patientBankVo.bankName,
    "birthday": new Date(patientBankVo.birthday).getTime(),
    "phone": patientBankVo.phone,
    "sex": patientBankVo.sex,
    "updateTime": dateP
  }
  let patientRecordsVo = {
    "docterSuggest": submitRef.docterSuggest,
    "hospital": "云诊所",
    "infect": submitRef.infect,
    "mainSuit": submitRef.mainSuit,
    "message": submitRef.message,
    "personalRecordsId":patientBankVo.bankId,
    "recordType": submitRef.recordType,
    "recordsId": recordsId,
    "recordsTime": new Date(submitRef.recordsTime).getTime(),
    "remarks": submitRef.remarks
  };
  let money = 0;
  //遍历处方表
  let listRxVo:any = [];

  submitRxs.forEach((rxItem: any) => {
    
    if(rxItem.item.length>0){
      rxItem.item.forEach((drugItem: any) => {
      listRxVo.push({
        "amount": drugItem.amount,
        "drugName": drugItem.drugName,
        "drugNumber": drugItem.drugNumber,
        "measure": rxItem.rx.measure,
        "medicationRequirements":  rxItem.rx.medicationRequirements,
        "price": drugItem.price,
        "recordsId": patientRecordsVo.recordsId,
        "remarks": rxItem.rx.remarks,
        "rxDay":  rxItem.rx.rxDay,
        "rxDosage":  rxItem.rx.rxDosage,
        "rxName":  rxItem.rx.rxName,
        "rxTotalDay":  rxItem.rx.rxTotalDay,
        "rxTotalDosage":  rxItem.rx.rxTotalDosage,
        "rxType":  rxItem.rx.rxType,
        "rxId": rxItem.rx.rxId,
      })
      money+=drugItem.amount
    });
    }
  });
  let seeDoctorVo = {
    "doctor": store.state.router.userData.userInfo.empUserName,
    "id": seeDoctorId,
    "money": money,
    "recordsId": patientRecordsVo.recordsId,
    "seeDoctorTime": dateP,
    "status": 0
  }
  createTreat({
   listRxVo:listRxVo,
    patientRecordsVo:patientRecordsVo,
    seeDoctorVo:seeDoctorVo,
    patientBankVo:patientBankVo
  })
  ElMessage({
      message: "新建就诊单成功！",
      type:"success"
    });

}
function PrefixInteger(num:any, length:any) {
  return (Array(length).join('0') + num).slice(-length);
 }
 function getRandomStr(length:any){
  let num = PrefixInteger(Math.floor(Math.random()*1000000),length)
  return new Date().toLocaleDateString().replaceAll("/","")+num
 }
 const searchTel = async ()=>{
  const tel =  patientInfo.value.phone
  await axios({
      url:"/seeDoctor/newVisits/selectPatientBankRecordsByPhone",
      method:"get",
      params:{
        phone:tel
      }
      }).then((res:any)=>{
        console.log(res);
        
        // store.state.createTreat.patientInfo=res.data.data
      }).catch(err=>{
        console.log(err);
      })
  // patientInfo.value = patientInfoNet.value
 }
const options = [
  {
    value: "男",
    label: "男",
  },
  {
    value: "女",
    label: "女",
  },
];
const gridData = [
  {
    bankName: "老鼠",
    phone: "2001-11-1",
    recordsTime: "急诊",
    status: "否",
  },
  {
    bankName: "老鼠",
    phone: "2001-11-1",
    recordsTime: "急诊",
    status: "否",
  },
  {
    bankName: "老鼠",
    phone: "2001-11-1",
    recordsTime: "急诊",
    status: "否",
  },
];

const table = ref(false);
const dialogTableVisible = ref(false);
const input4 = ref("");
const form1 = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
});


const form = reactive({
  name: "",
  region: "",
  tel: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
  history: "",
});
let btn1 = ref("btnOne");
let btn2 = ref("btnTwo");
let btn3 = ref("btnOne");
let btn4 = ref("btnTwo");
let btn5 = ref("btnOne");
let btn6 = ref("btnTwo");
const flag = ref(true);
const flagOne = ref(true);
const flagTwo = ref(true);
// 左边切换按钮
const patientFile = () => {
  btn1.value = "btnOne";
  btn2.value = "btnTwo";
  flag.value = true;
};
const historicalCase = () => {
  btn1.value = "btnTwo";
  btn2.value = "btnOne";
  flag.value = false;
};
// 弹框切换按钮
const Registration = () => {
  btn5.value = "btnOne";
  btn6.value = "btnTwo";
  flagTwo.value = true;
};
const Patient = () => {
  btn5.value = "btnTwo";
  btn6.value = "btnOne";
  flagTwo.value = false;
};
// 右边切换按钮
const caseOne = () => {
  btn3.value = "btnOne";
  btn4.value = "btnTwo";
  flagOne.value = true;
};
const prescription = () => {
  btn3.value = "btnTwo";
  btn4.value = "btnOne";
  flagOne.value = false;
};
</script>
<style scoped>
#inputk {
  width: 200px;
}

#name {
  position: absolute;
  left: 190px;
}

#r_inner {
  margin: 25px;
}

#content_right {
  background-color: white;
  width: 100%;
}

#nav {

  display: flex;
}

#left>span {
  font-size: 18px;
  font-weight: 200;
  color: #606266;
}

#word {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

#sex {
  display: flex;
  justify-content: center;

  margin-left: 55px;
  margin-bottom: 20px;
}

.input-with-select1 {
  height: 30px;
  width: 300px;
  margin-right: 20px;
}

#right>.el-button {
  margin-left: 10px;
}

.mt-4 {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.input-with-select {
  width: 300px;
}

#gua {
  width: 100%;
}

#huan {
  width: 100%;
}

#f {
  display: flex;
  justify-content: space-between;
}

#f_left {
  width: 230px;

}

#f_right {
  margin-top: 5px;
}

#f_right>span {
  font-size: 14px;
  color: #606266;
}

#li {
  width: 100px;
  height: 40px;
  line-height: 40px;
}

#p_form {
  width: 360px;
  margin-top: 20px;
  display: flex;
  align-items: center;
}

#content {
  margin-top: 10px;
  display: flex;
}

#title {
  margin-top: 20px;
}

#blue {
  color: #429bff;
  font-weight: 600;

  margin-left: 55px;
}

#total {

  display: flex;
  flex-direction: column;
}

#top {
  display: flex;
  justify-content: space-between;
  align-items: center;

  margin-top: 10px;
}

#top>div {
  display: flex;
}

#content_left {
  display: flex;
  flex-flow: column;
  width: 400px;
  background-color: #f8f8f8;
}

/* 切换按钮 */
ul {
  display: flex;
  justify-content: center;
  margin: 0;
  padding: 0;
  height: 40;
  list-style: none;
  text-align: center;
}

ul li {
  width: 227px;
  height: 40px;
  line-height: 40px;
  background-color: #e5e5e5;
  color: #676a6d;
  /* text-decoration: none; */
}

.btnOne {
  background-color: #00aaff;
  color: white;
}

.btnTwo {
  background-color: #e5e5e5;
  color: #676a6d;
}
</style>
  